const { getDayString } = require('../util')
Parse.Cloud.beforeSave('QlOrder', async (req, res) => {
  try {
    const order = req.object
    const preOrder = await new Parse.Query('QlOrder').equalTo('objectId', order.id).include('product').first()
    const status = order.get('status')
    const preStatus = preOrder.get('status')

    if (preOrder && status === 1 && preStatus === 0) {
      const vip = preOrder.get('product')
      const buyCount = vip.get('buyCount') || 0
      vip.set('buyCount', buyCount + 1)

      const day = getDayString()
      const orderCount = await new Parse.Query('QlOrderCount').equalTo('day', day).equalTo('vip', vip).first() || new Parse.Object('QlOrderCount')
      const total = orderCount.get('total') || 0
      orderCount.set('total', total + 1).set('vip', vip).set('day', day)
      await Parse.Object.saveAll([vip, orderCount])
    }
  } catch (err) {
    console.log(err)
  } finally {
    res.success()
  }
})

Parse.Cloud.beforeSave('QlGroup', async (req, res) => {
  const group = req.object
  try {
    if (!group.id) {
      const user = group.get('user')
      const day = getDayString()
      const findAccount =  new Parse.Query('QlAccount').equalTo('user', user).first()
      const findUseCount = new Parse.Query('QlUseCount').equalTo('day', day).first()
      const findUseTotalCount = new Parse.Query('QlUseTotalCount').first()
      const account = await findAccount
      const useCount = await findUseCount || new Parse.Object('QlUseCount')
      const useTotalCount = await findUseTotalCount || new Parse.Object('QlUseTotalCount')

      if (account) {
        const useNum = useCount.get('use') || 0
        const tryNum = useCount.get('try') || 0
        const useTotal = useTotalCount.get('use') || 0
        const tryTotal = useTotalCount.get('try') || 0
        const isVip = !!account.get('vip')

        useCount.set('day', day)

        if (isVip) {
          useCount.set('use', useNum + 1)
          useTotalCount.set('use', useTotal + 1)
        } else {
          useCount.set('try', tryNum + 1)
          useTotalCount.set('try', tryTotal + 1)
        }

        await Parse.Object.saveAll([useCount, useTotalCount])
      }
    }
  } catch (err) {
    console.log(err)
  } finally {
    res.success()
  }
})

